package il.technion.cs236369.webserver;

import il.technion.cs236369.webserver.components.ConnectionListener;
import il.technion.cs236369.webserver.components.IConnectionListener;
import il.technion.cs236369.webserver.components.IDataHandler;
import il.technion.cs236369.webserver.components.INewWebRequest;
import il.technion.cs236369.webserver.configuration.IServerConfiguration;
import il.technion.cs236369.webserver.configuration.ServerConfiguration;
import il.technion.cs236369.webserver.handlers.WebRequestHandler;
import il.technion.cs236369.webserver.handlers.QueueHttpServerConnectionHandler;

import java.io.File;
import java.io.IOException;

import javax.net.ServerSocketFactory;

import org.apache.http.HttpServerConnection;

public class WebServer extends AbstractWebServer {

	private IConnectionListener connectionListener;
	
	WebServer(ServerSocketFactory srvSockFactory, int port, String baseDir,
			String welcomeFile, int numSocketReaders, int numRequestHandlers,
			int sizeSocketQueue, int sizeRequestQueue)
			throws ClassNotFoundException {
		super(srvSockFactory, port, baseDir, welcomeFile, numSocketReaders,
				numRequestHandlers, sizeSocketQueue, sizeRequestQueue);

		try {
			IServerConfiguration config = new ServerConfiguration("config.xml");
			IDataHandler<INewWebRequest> newRequestsHandler =  new WebRequestHandler(config, baseDir, welcomeFile);
			IDataHandler<HttpServerConnection> queueSocketHandler = new QueueHttpServerConnectionHandler(sizeRequestQueue, numRequestHandlers, newRequestsHandler);
			connectionListener = new ConnectionListener(srvSockFactory, port, sizeSocketQueue, numSocketReaders, queueSocketHandler);
		} catch (Exception e) {
			// TODO What to do???
			e.printStackTrace();
		}
	}

	@Override
	public void bind() throws IOException {
		// Add your code here
	}

	@Override
	public void start() {
		connectionListener.start();
	}

	public static void main(String[] args) throws Exception {
		/*Properties p = new Properties();
		p.load(new FileInputStream("config"));
		Injector inj = Guice.createInjector(new WebServerModule(p));
		IWebServer server = inj.getInstance(WebServer.class);
		server.bind();
		server.start();*/
		
		String basePath = new File(".").getAbsolutePath() + "\\serverBase";
		IWebServer server = new WebServer(ServerSocketFactory.getDefault(), 8080, basePath, "index.html", 3, 7, 100, 200);
		server.bind();
		server.start();

	}
}
